package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public ResultInfo login(String username, String password) {
        Employee employee = employeeMapper.findByUsername(username);
        if (employee==null) {
            return ResultInfo.error("员工不存在");
        }
        String password1 = employee.getPassword();
        String s = SecureUtil.md5(password);
        if (!StrUtil.equals(s,password1)) {
            return ResultInfo.error("密码错误");
        }
        if (employee.getStatus()!=1) {
            return ResultInfo.error("用户被冻结，请联系管理员！");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findList(String name) {
        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) { //添加员工
        //补齐员工参数
        long id = IdUtil.getSnowflake(1, 1).nextId();
        String md5Pwd = SecureUtil.md5("123456");
        employee.setId(id);
        employee.setPassword(md5Pwd);
        employee.setStatus(Employee.STATUS_ENABLE);
       /* employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        Employee employee=employeeMapper.findById(id);
        return employee;
    }

    @Override
    public void update(Employee employee) {
        /*employee.setUpdateUser(1L);
        employee.setUpdateTime(new Date());*/
        //employeeMapper.update(employee);
        employeeMapper.updateById(employee);
    }
}
